package com.weixin.cp.controller;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.weixin.cp.config.WxCpConfiguration;

import ops.weixin.cp.bean.WxCpDepart;
import ops.weixin.cp.bean.WxCpMessage;
import ops.weixin.cp.bean.WxCpMessageSendResult;
import ops.weixin.cp.bean.WxCpUser;

/**
 * 发送消息接口示例
 * 
 * 浏览器访问：http://{可访问的域名或IP}/wx/message?email=zhengbl@founder.com.cn&&content=消息内容
 * 
 * @author SuM
 * @date: 2019年12月24日下午4:08:23
 */
@RestController
@RequestMapping("/wx/message")
public class WxSendTestController {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	/**
	 * 发送消息： 单条发送
	 */
	@GetMapping(produces = "text/plain;charset=utf-8")
	public String sendMsg(@RequestParam(name = "email", required = false) String email,
			@RequestParam(name = "content", required = false) String content) {
		try {
			this.logger.info("\n接收到来自浏览器消息：email = [{}], content = [{}]", email, content);

			// 所见部门列表
			List<WxCpDepart> departList = WxCpConfiguration.getCpService().getDepartmentService().list(null);
			if (departList == null || departList.size() <= 0)
				return "应用未配置可见部门";
			
			logger.debug("应用可见部门列表：" + departList.size() + ",  " + departList.toString());
			for (WxCpDepart cpDepart : departList) {
				List<WxCpUser> users = WxCpConfiguration.getCpService().getUserService().listByDepartment(cpDepart.getId(),
						false, 0);
				for (WxCpUser cpUser : users) {
					if (cpUser.getEmail().equals(email)) {
						return sendTextMessage(cpUser.getUserId(), content);
					}
				}
			}
			return "未找到发送用户";
		} catch (Exception e) {
			return e.getMessage();
		}
	}

	/**
	 * 文本消息
	 * 
	 * user/party/tag 三个至少填一个
	 */
	private String sendTextMessage(String userId, String content) {
		try {
			WxCpMessage message = WxCpMessage.TEXT().agentId(WxCpConfiguration.getWxCpProperties().agentId) // 自建应用ID
					.toUser(userId) // 非必填，UserID列表（消息接收者，多个接收者用‘|’分隔）。特殊情况：指定为@all，则向关注该企业应用的全部成员发送
					// .toParty("非必填，PartyID列表，多个接受者用‘|’分隔。当touser为@all时忽略本参数")
					// .toTag("非必填，TagID列表，多个接受者用‘|’分隔。当touser为@all时忽略本参数")
					.content(content).build();

			WxCpMessageSendResult result = WxCpConfiguration.getCpService().messageSend(message);
			return "文本发送结果： " + result.getErrmsg();
		} catch (Exception e) {
			e.printStackTrace();
			return e.getMessage();
		}
	}
}
